package com.czl.module_base.activity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import com.czl.base.adapter.ViewPagerFmAdapter;
import com.czl.module_base.databinding.ActivityBaseTabBinding;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;

import java.util.ArrayList;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * @author by xubin,
 * @date on 2022/1/24.
 * PS: Not easy to write code, please indicate.
 */
public abstract class BaseTabActivity extends BaseActivity<ActivityBaseTabBinding> {

    @Override
    protected ActivityBaseTabBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityBaseTabBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        binding.tabLayout.setTabData(mTabEntities());
        BaseViewPagerAdapter adapter = new BaseViewPagerAdapter(getSupportFragmentManager(), fragments());
        binding.viewPager2.setAdapter(adapter);
        binding.tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                binding.viewPager2.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        binding.viewPager2.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                binding.tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    protected abstract List<SupportFragment> fragments();

    protected abstract ArrayList<CustomTabEntity> mTabEntities();

    private static class BaseViewPagerAdapter extends FragmentPagerAdapter {

        private final List<SupportFragment> fragments;

        BaseViewPagerAdapter(FragmentManager fm, List<SupportFragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments != null ? fragments.size() : 0;
        }
    }
}
